<template>
  <Header :addItem="addItem" />

  <List :todoList="todoList" :checkItem="checkItem" :delItem="delItem" />

  <Footer :todoList="todoList" :checkAll="checkAll" :clearItem="clearItem" />
</template>

<script>
import Header from './components/Header.vue';
import List from './components/List.vue';
import Footer from './components/Footer.vue';

import { getCurrentInstance } from 'vue';
export default {
  name: 'App',
  components: {
    Header,
    List,
    Footer,
  },
  setup(prop) {
    // const data = reactive({
    //   todoList: [
    //     {id: 1, title: '追风亚索', checked: false},
    //     {id: 2, title: '儿童劫', checked: true},
    //     {id: 3, title: '光辉女郎', checked: false},
    //     {id: 4, title: '无双剑姬', checked: false},
    //     {id: 5, title: '灌篮高手', checked: true},
    //     {id: 6, title: '勇敢牛牛', checked: false},
    //   ]
    // })

    const { proxy } = getCurrentInstance();
    const data = proxy.$reactive({
      todoList: [],
    });
    console.info(data);
    // 初始化数据
    proxy.$onMounted(() => {
      setTimeout(() => {
        data.todoList = proxy.$local.get('todos');
      }, 500);
    });

    const addItem = (item) => {
      if (data.todoList) data.todoList.unshift(item);
      else data.todoList = [item];
    };

    const checkItem = (item, checked) => {
      console.info({ ...item });
      item.checked = checked;
    };

    const delItem = (index) => {
      data.todoList.splice(index, 1);
    };

    // 全选/全不选/反选
    const checkAll = (checked) => {
      data.todoList.forEach((item, key) => {
        item.checked = !item.checked;
      });
    };

    // 清除完成待办: length 存在选中项，才遍历数据
    const clearItem = (length) => {
      if (!length) return;
      data.todoList = data.todoList.filter((item) => !item.checked);
    };

    // 监听到待办事项数据发生变化，就保存数据
    proxy.$watch(
      () => data.todoList,
      (value) => {
        proxy.$local.set('todos', value);
      },
      { deep: true }
    );
    // proxy.$watchEffect(() => {
    //   local.set('todos', data.todoList)
    // })

    return {
      ...proxy.$toRefs(data),

      addItem,
      checkItem,
      delItem,

      checkAll,
      clearItem,
    };
  },
};
</script>
